package com.fanh.service.impl;


import com.fanh.common.api.CommonPage;
import com.fanh.common.util.CommonUtil;
import com.fanh.common.util.FileUtil;
import com.fanh.dao.GuideCourseDao;
import com.fanh.dao.GuideLessonDao;
import com.fanh.dto.*;
import com.fanh.mapper.*;

import com.fanh.model.*;
import com.fanh.service.GuideCourseService;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;


@Service("guideCourseService")
public class GuideCourseServiceImpl implements GuideCourseService {

    private Logger LOGGER = LoggerFactory.getLogger(GuideCourseServiceImpl.class);



    @Value("${minio.endpoint}")
    private String ENDPOINT;
    @Value("${minio.bucketName}")
    private String BUCKET_NAME;
    @Value("${minio.accessKey}")
    private String ACCESS_KEY;
    @Value("${minio.secretKey}")
    private String SECRET_KEY;
    @Value("${minioInternet.endpoint}")
    private String minioInternet;


    @Autowired
    private GuideContentMapper guideContentMapper;
    @Autowired
    private GuideCommentMapper guideCommentMapper;
    @Autowired
    private GuideCommentFileMapper guideCommentFileMapper;
    @Autowired
    private GuideCourseMapper guideCourseMapper;

    @Autowired
    private GuideLessonMapper guideLessonMapper;
    @Autowired
    private GuidePayMapper guidePayMapper;
    @Autowired
    private GuideReadHistoryMapper guideReadHistoryMapper;
    @Autowired
    private GuideCourseDao guideCourseDao;

    @Override
    public GuideContent getGuideContentById(String lessonId) {
        GuideContentExample example = new GuideContentExample();
        example.createCriteria().andLessonIdEqualTo(lessonId).andCurrentEqualTo("1");
      List<GuideContent> list =  guideContentMapper.selectByExampleWithBLOBs(example);
      if(list!=null && list.size()>0){
          GuideContent content =list.get(0);
          if(content.getContent() == null ){
              return  content;
          }
          content.setContent(content.getContent().replaceAll("class=guide-comment", "class='guide-comment' onclick='display(this)' "));
          return content;
      }
        return null;
    }

    @Override
    public List<GuideCommentResult> getGuideCommentBycontentId(String lessonId) {

        List<GuideCommentResult> result = new ArrayList<GuideCommentResult>();
        //查询课程
        GuideContent courseContent = getGuideContentById(lessonId);

        if(courseContent == null ){
            return  null ;
        }
        //根据课程查询文章
        GuideCommentExample example = new  GuideCommentExample();
        example.createCriteria().andContentIdEqualTo(courseContent.getId());
        example.setOrderByClause(" create_date asc");
        //查询所有批注
        List<GuideComment> guideCommentsuideComment = guideCommentMapper.selectByExample(example);

        if(guideCommentsuideComment== null && guideCommentsuideComment.size()<1){
            return null;
        }
        //查询批注下面的附件
        GuideCommentFileExample fileExample = new GuideCommentFileExample();
        for(GuideComment guideComment : guideCommentsuideComment) {
            GuideCommentResult commentResult = new GuideCommentResult();
            BeanUtils.copyProperties(guideComment,commentResult);
            fileExample.clear();
            fileExample.createCriteria().andCommentIdEqualTo(guideComment.getId());
            fileExample.setOrderByClause("create_date asc");
             List<GuideCommentFile> commentFiles = guideCommentFileMapper.selectByExample(fileExample);
            for(GuideCommentFile ccf : commentFiles) {
                if(!ccf.getType().equals("text")){
                    String url = minioInternet + "/" + BUCKET_NAME + "/" + ccf.getCourseId()+"/"+ccf.getLessonId()+"/"+ccf.getName();
                    ccf.setName(url);
                 //   ccf.setName("/userfiles/guide/"+ccf.getCourseId()+"/"+ccf.getLessonId()+"/"+ccf.getName());
                }
                if(!StringUtils.isEmpty(ccf.getVideoImage())) {
                    String url = minioInternet + "/" + BUCKET_NAME + "/" + ccf.getCourseId()+"/"+ccf.getLessonId()+"/"+ccf.getVideoImage();
                    ccf.setVideoImage(url);
                   // ccf.setVideoImage("/userfiles/guide/"+ccf.getCourseId()+"/"+ccf.getLessonId()+"/"+ccf.getVideoImage());
                }
            }
            commentResult.setCommentFiles(commentFiles);
            result.add(commentResult);
        }

        return result;
    }

    @Override
    public CommonPage<GuideCourse> getCourseList(String userId, int pageNo, int PageSize) {
        PageHelper.startPage(pageNo,PageSize);
        GuideCourseExample example = new GuideCourseExample();
        example.createCriteria().andTeacherIdEqualTo(userId);
        return CommonPage.restPage(guideCourseMapper.selectByExample(example));
    }

    @Override
    public String fileUpload(MultipartFile commentFile, GuideCommentFile courseCommentFile) {
        String customPath=courseCommentFile.getCourseId()+"/"+courseCommentFile.getLessonId();
        String url = FileUtil.upload(customPath,commentFile,ENDPOINT,BUCKET_NAME,ACCESS_KEY,SECRET_KEY,minioInternet);
        return url;
    }

    @Override
    public int uploadComment(LessonCommentParam lessonCommentParam) {

        //1、保存新的内容
        GuideLesson lesson = guideLessonMapper.selectByPrimaryKey(lessonCommentParam.getLessonId());

        GuideContent guideContent = new GuideContent();
        guideContent.setContent(lessonCommentParam.getContent());
        guideContent.setCourseId(lesson.getCourseId());
        guideContent.setLessonId(lesson.getId());
        guideContent.setCurrent("0");
        guideContentMapper.insertSelective(guideContent);

        //2.保存批注
        List<GuideCommentParam> comments = lessonCommentParam.getComments();

        for(GuideCommentParam comment : comments) {
            comment.setId(CommonUtil.uuid());
            comment.setCourseId(lesson.getCourseId());
            comment.setLessonId(lesson.getId());
            comment.setContentId(guideContent.getId());
            comment.setCreateDate(new Date());
            guideCommentMapper.insertSelective(comment);

            //3.保存批注文件
            List<GuideCommentFile> commentFiles = comment.getCommentFiles();
            for(GuideCommentFile commentFile : commentFiles) {

                //客户端保证文件先传上来
                commentFile.setId(CommonUtil.uuid());
                commentFile.setUploadStatus(0);
                commentFile.setCourseId(lesson.getCourseId());
                commentFile.setLessonId(lesson.getId());
                commentFile.setCommentId(comment.getId());
                commentFile.setCreateDate(new Date());
                guideCommentFileMapper.insertSelective(commentFile);
            }
        }

        GuideLesson guideLesson = guideLessonMapper.selectByPrimaryKey(lessonCommentParam.getLessonId());
        guideLesson.setStatus(3);
        return guideLessonMapper.updateByPrimaryKey(guideLesson);

    }

    @Override
    public Map<String, Object> paycheck(String userId, String courseId) {
        Map<String, Object> result = new HashMap<>();
        GuideCourse course = guideCourseMapper.selectByPrimaryKey(courseId);
        if(course.getFree() == 1){ //如果课程免费直接返回，不检测是否支付过
            result.put("free", 1);

        } else {
            //不是免费，需要检测是否支付过
            result.put("free", 0);
            GuidePayExample coursePayExample = new GuidePayExample();
            coursePayExample.createCriteria().andCourseIdEqualTo(courseId)
                    .andUserIdEqualTo(userId);
            List<GuidePay> pays = guidePayMapper.selectByExample(coursePayExample);
            if(pays!=null && pays.size()>0) {
                result.put("payed", 0);
                result.put("overdue", 0);
            } else {
                result.put("payed", 1);

                int overdue = 1;
                if(course.getType().equals("2")) {//固定
                    overdue = 0;
                } else {
                    Date now = new Date();
                    for(GuidePay pay : pays) {
                        if(pay.getEndDate().after(now)) {
                            overdue = 0;
                            break;
                        }
                    }
                }
                result.put("overdue", overdue);
            }
        }

        GuideReadHistoryExample courseReadHistoryExample = new GuideReadHistoryExample();
         courseReadHistoryExample.createCriteria().andCourseIdEqualTo(courseId);
         List<GuideReadHistory> list = guideReadHistoryMapper.selectByExample(courseReadHistoryExample);

        if(list!=null && list.size()>0){
            result.put("lastRead", list.get(0).getLessonId());
        }else{
            result.put("lastRead", null);
        }

        return result;
    }

    @Override
    public List<GuideCourse> readHistory(String userId, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo,pageSize);
        return guideCourseDao.userReadCourse(userId);

    }

    @Override
    public List<GuideCourseResult> findList(GuideCourseParam course, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo,pageSize);
        return guideCourseDao.findList(course);
    }

    @Override
    public List<GuideCourseResult> findList(GuideCourseParam course) {
        return guideCourseDao.findList(course);
    }

    @Override
    public List findListNames(String name,String publish, int pageNo, int pageSize) {
        PageHelper.startPage(pageNo,pageSize);
        GuideCourseExample example = new GuideCourseExample();
        GuideCourseExample.Criteria criteria = example.createCriteria();
        if(name!=null && !name.isEmpty()){
            criteria.andNameEqualTo(name);
        }
        if(publish!=null && !publish.isEmpty()){
            criteria.andPublishEqualTo(publish);
        }
        List<GuideCourse> list = guideCourseMapper.selectByExample(example);
        if(list!=null && list.size()>0){
           return list.stream().map(guideCourse -> guideCourse.getName()).collect(Collectors.toList());
        }
        return null;
    }
}
